package com.va.feedback.component;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.RelativeLayout;

import com.va.feedback.FeedbackItemConstants;
import com.va.feedback.widget.CheckboxGroup;

public class CheckboxFeedback extends AbstractFeedback {

	private Context context;
	private CheckboxGroup checkList;

	/**
	 * Constructor for CheckboxFeedback
	 * @param context context of the parent
	 */
	public CheckboxFeedback(Context context) {
		super(context);
		this.context = context;

		addQuestionWidget();
		addAnswerComponent();
	}

	/**
	 * Sets the properties
	 */
	@SuppressWarnings("unchecked")
	public void setComponentProperty(String type, Object value) {
		if (FeedbackItemConstants.PROPERTY_QUESTION.equals(type)) {
			String question = (String) value;
			questionWidget.setText(question);
		} else if (FeedbackItemConstants.PROPERTY_CHECKBOX_ITEMS.equals(type)) {
			List<String> items = (ArrayList<String>) value;
			for (String item : items) {
				checkList.addCheckbox(item);
			}
		}
	}

	/**
	 * Adds the component which captures the user response to the question widget
	 */
	protected void addAnswerComponent() {
		checkList = new CheckboxGroup(context);
		RelativeLayout.LayoutParams checkListLayout = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		checkList.setId(2);
		checkListLayout.addRule(RelativeLayout.BELOW, 1);
		this.addView(checkList, checkListLayout);
	}

	/**
	 * Returns the response in the form of a JSONObject
	 * The response is : {'qid': qid, 'answer':['option1','option2',...]}
	 */
	public JSONObject getFeedback() throws JSONException {
		List<String> checkedItems = checkList.getCheckedItems();
		if (checkedItems.isEmpty())
			return null;
		JSONArray checked = new JSONArray(checkedItems);
		JSONObject object = new JSONObject();
		object.put("qid", qid);
		object.put("answer", checked);
		return object;
	}

}
